#include "framework.h"
#include "graphics/directx9/renderer_directx9.h"

namespace gecko
{

Framework::Framework()
	: TheRenderer(NULL)
	, TheInputManager(NULL)
{

}

bool Framework::Initialise(int width, int height, int bpp, bool fullscreen)
{
	m_window = new gecko::Window;
	m_window->Initialise(width, height, bpp, fullscreen);

	TheInputManager = CreateInputManager();
	TheInputManager->Initialise();
	m_window->SetInputMananger(TheInputManager);

	TheRenderer = new Renderer_DirectX9;
	TheRenderer->Initialise(width, height, bpp, fullscreen);
	TheRenderer->SetClearColour(gecko::Colour::Blue());

	m_frameTimer = new FrameTimer;
	m_frameTimer->Start();

	m_debugShader = new Effect_Debug(TheRenderer);

	// call game-code
	OnInitialise();

	return true;
}

bool Framework::Destroy()
{
	TheInputManager->Destroy();
	TheRenderer->Destroy();
	m_window->Destroy();

	delete TheInputManager;
	delete m_frameTimer;
	delete TheRenderer;
	delete m_window;

	return true;
}

void Framework::Run(int width, int height, int bpp, bool fullscreen)
{
	Initialise(width, height, bpp, fullscreen);

	while ( m_window->Run() )
	{
		// update
		TheInputManager->Update(m_frameTimer->GetSecsPerFrame());
		OnUpdate(m_frameTimer->GetSecsPerFrame());

		// render (TODO: break out into render thread)
		TheRenderer->BeginScene();
		TheRenderer->Clear();
		OnRender(TheRenderer);
		TheRenderer->RenderBatchedGeometry();
		TheRenderer->RenderDebugLines(m_debugShader);
		TheRenderer->EndScene();
		TheRenderer->Present();

		// end frame
		m_frameTimer->Frame();
	}

	Destroy();
}

}
